package com.tywj.lib.core.common.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.ACTIVITY_SERVICE
import android.content.pm.PackageManager
import android.os.Build
import com.blankj.utilcode.util.AppUtils
import com.tywj.lib.core.common.manager.ActivityManager
import org.jetbrains.anko.runOnUiThread

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/7
 *     desc   : App工具类
 *     version: 1.0.0
 * </pre>
 */
@SuppressLint("StaticFieldLeak")
object AppUtil {

    // 当前运行环境，默认为开发环境
    var isRelease = false
        internal set

    lateinit var context: Context

    fun isDev(): Boolean = !isRelease

    fun getMetaData(key: String): String {
        val appInfo = context.packageManager.getApplicationInfo(
            context.packageName, PackageManager.GET_META_DATA)
        return appInfo.metaData.getString(key) ?: ""
    }

    fun getVersionName(): String = AppUtils.getAppVersionName(context.packageName)

    fun getVersionCode(): Int = AppUtils.getAppVersionCode(context.packageName)

    fun runOnUiThread(action: () -> Unit) {
        context.runOnUiThread { action.invoke() }
    }

    @Suppress("DEPRECATION")
    fun moveAppToFront() {
        if (!AppUtils.isAppForeground()) {
            val am = context.getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val taskList = am.appTasks
                if (taskList.isNotEmpty()) {
                    taskList.first().moveToFront()
                }
            } else {
                val taskList = am.getRunningTasks(1000)
                for (task in taskList) {
                    if (task.topActivity.packageName == (context.packageName)) {
                        am.moveTaskToFront(task.id, 0)
                        return
                    }
                }
            }
        }
    }

    fun exitApp() {
        ActivityManager.closeAllActivity()
        AppUtils.exitApp()
    }
}
